<?php
class List_buku extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');
		$this->load->model('perpus/pustaka_model');
		$this->load->model('perpus/refrensi_model');
		$this->load->helper(array('form', 'url'));
		$this->load->library('upload');
	}
	
	function index()
	{
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['no'] = array('No',40,TRUE,'center',0);
		if($this->session->userdata('roleid')=='0'){ //diknas
			$colModel['NAMA_SEKOLAH'] = array('Nama Sekolah',100,TRUE,'center',1);
		}
		$colModel['JUDUL_BUKU'] = array('Judul Pustaka',300,TRUE,'center',1);
		$colModel['NAMA_PENULIS'] = array('Pengarang',200,TRUE,'center',1);
		$colModel['NAMA_RAK'] = array('Rak',80,TRUE,'center',1);
		$colModel['NAMA_PENERBIT'] = array('Penerbit',100,TRUE,'center',1);
		$colModel['NAMA_KATALOG'] = array('Katalog',150,TRUE,'center',1);
		$colModel['TAHUN_TERBIT'] = array('Tahun Terbit',60,TRUE,'center',1);
		$colModel['JML_EKSEMPLAR'] = array('Jumlah Eksemplar',90,TRUE,'center',0);
		$colModel['ubah'] = array('Edit',30,FALSE,'center',0);
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '345',
		'rp' => 10,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Buku'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$buttons[] = array('Add','add','org_js');
		$buttons[] = array('Delete','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Select All','add','org_js');
		$buttons[] = array('Deselect All','delete','org_js');
		$buttons[] = array('separator');
		$buttons[] = array('Lihat Daftar Eksemplar','view','org_js');
		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("perpus/list_buku/listbuku_grid/"),$colModel,'no','asc',$gridParams,$buttons);
		
		if($this->session->flashdata('suc_msg'))
			$data['header_info'] = '<div class="ret_success">'.$this->session->flashdata('suc_msg').'</div>';
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function org_js(com,grid)
			{
				if (com=='Select All')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Deselect All')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Add')
				{
					location.href='".base_url()."index.php/perpus/list_buku/input_buku/'; 
				}
				
				if (com=='Lihat Daftar Eksemplar')
				{
					location.href='".base_url()."index.php/perpus/list_eksemplar/'; 
				}
				
				if (com=='Delete')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/perpus/list_buku/delete_buku')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}				
			}
			
			function lihatEks(idpustaka){
				popup('".base_url()."index.php/perpus/list_buku/lihat_eks/'+idpustaka,600,500);
			}
			
			function popup(url,width,height) 
			{
				 var left   = (screen.width  - width)/2;
				 var top    = (screen.height - height)/2;
				 var params = 'width='+width+', height='+height;
				 params += ', top='+top+', left='+left;
				 params += ', directories=no';
				 params += ', location=no';
				 params += ', menubar=no';
				 params += ', resizable=no';
				 params += ', scrollbars=yes';
				 params += ', status=no';
				 params += ', toolbar=no';
				 newwin=window.open(url,'windowname5', params);
				 if (window.focus) {newwin.focus()}
				 return false;
			}			
			</script>
			";	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
	}
	
	function listbuku_grid()
	{
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		if($this->session->userdata('roleid')=='0') //diknas
			$valid_fields = array('NAMA_SEKOLAH','JUDUL_BUKU','NAMA_PENULIS');
		else	
			$valid_fields = array('JUDUL_BUKU','NAMA_PENULIS','NAMA_RAK','NAMA_PENERBIT','NAMA_KATALOG','TAHUN_TERBIT');
		
		$this->flexigrid->validate_post('ID_BUKU','asc',$valid_fields);

		$records = $this->pustaka_model->get_buku();
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 0;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			if($this->session->userdata('roleid')=='0'){ //diknas{
				$record_items[] = array($row->ID_BUKU,
				$no+1,
				'<div align="center">'.$row->NAMA_SEKOLAH.'</div>',
				'<div align="center">'.$row->JUDUL_BUKU.'</div>',
				'<div align="center">'.$row->NAMA_PENULIS.'</div>',
				'<div align="left">'.$row->jmleks.'</div>',
				'<a href=\''.site_url().'/perpus/list_buku/edit_buku/'.$row->ID_BUKU.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> '
				);
				$no++;
			}else{
				$record_items[] = array($row->ID_BUKU,
				$no+1,
				'<div align="left">'.$row->JUDUL_BUKU.'</div>',
				'<div align="left">'.$row->NAMA_PENULIS.'</div>',
				'<div align="left">'.$row->NAMA_RAK.'</div>',
				'<div align="left">'.$row->NAMA_PENERBIT.'</div>',
				'<div align="left">'.$row->NAMA_KATALOG.'</div>',
				'<div align="left">'.$row->TAHUN_TERBIT.'</div>',
				'<div align="center"><a title="Lihat Eksemplar!" href=\'javascript:lihatEks("'.$row->ID_BUKU.'")\'><img border=\'0\' src=\''.base_url().'images/magnifier.png\'></a>&nbsp;&nbsp;<a title="Tambahkan Eksemplar!" href=\''.site_url().'/perpus/list_buku/tambah_eks/'.$row->ID_BUKU.'/\'><img border=\'0\' src=\''.base_url().'images/add.png\'></a>&nbsp;&nbsp;'.$row->jmleks.'</div>',
				'<a title="Edit data!" href=\''.site_url().'/perpus/list_buku/edit_buku/'.$row->ID_BUKU.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> '
				);
				$no++;
			}
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
		
	function cek_validasi() {	
			// Setting Rules
			if($this->session->userdata('roleid')=='0') //diknas
				$this->form_validation->set_rules('nama_sekolah', 'Nama Sekolah', 'required');
			
			$this->form_validation->set_rules('judul_buku', 'Judul Buku', 'required');
			// $this->form_validation->set_rules('kode_buku', 'Kode Pustaka', 'required');
			$this->form_validation->set_rules('id_jenis', 'Jenis Pustaka', 'required');
			$this->form_validation->set_rules('id_katalog', 'Nama Katalog', 'required');
			$this->form_validation->set_rules('id_penerbit', 'Penerbit', 'required');
			$this->form_validation->set_rules('id_penulis', 'Penulis', 'required');
			$this->form_validation->set_rules('jumlah', 'Jumlah', 'required|numeric');
			$this->form_validation->set_rules('tahun_terbit', 'Tahun Terbit', 'required|numeric');
			
			$this->form_validation->set_rules('hal_angka', 'Jumlah Hal. Angka', 'numeric');
			$this->form_validation->set_rules('dimensi', 'Dimensi', 'numeric');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			$this->form_validation->set_message('numeric', 'Kolom %s harus diisi dengan angka!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
	}
	
	function cek_buku($kode){
		$rs_cek = $this->pustaka_model->validasi_buku($kode)->row();
		return $rs_cek;
	}
	
	function input_buku()
    {
		if ($this->cek_validasi() == FALSE){
			$data['status'] = 'new';
			$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
			$data['katalog'] = $this->refrensi_model->get_list_katalog();
			$data['penulis'] = $this->refrensi_model->get_list_penulis();
			$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
			$data['kodebuku'] = str_pad(($this->pustaka_model->getLastPustaka()->row()->maxid) + 1,7,'0',STR_PAD_LEFT) ;
			
			$data['content'] = $this->load->view('perpus/form_buku',$data,true);
			$this->load->view('main',$data);
		}
		else{
			if($this->cek_buku($this->input->post('kode_buku'))->jml > 0){
				$data['status'] = 'new';
				$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
				$data['katalog'] = $this->refrensi_model->get_list_katalog();
				$data['penulis'] = $this->refrensi_model->get_list_penulis();
				$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
				$data['kodebuku'] = str_pad(($this->pustaka_model->getLastPustaka()->row()->maxid) + 1,7,'0',STR_PAD_LEFT) ;
				$data['value'] = $this->input->post();
				$data['err_msg'] = 'Data Pustaka tersebut telah ada dalam database.';
				$data['content'] = $this->load->view('perpus/form_buku',$data,true);
				$this->load->view('main',$data);
			}else{
				$this->insert_buku();
			}
		}            
    }
	
	function insert_buku(){
		if($this->session->userdata('roleid')=='0'){ //diknas
			$nama_sekolah = $this->input->post('nama_sekolah');
		}else{
			$nama_sekolah = $this->session->userdata('unitid');
		}
		
		$data = array(
			'ID_SEKOLAH'			=> $nama_sekolah,
			'JUDUL_BUKU'			=> $this->input->post('judul_buku'),
			'KODE_BUKU'				=> $this->input->post('kode_buku'),
			'ID_JENIS'				=> $this->input->post('id_jenis'),
			'ID_KATALOG'			=> $this->input->post('id_katalog'),
			'ID_PENULIS'			=> $this->input->post('id_penulis'),
			'ID_PENERBIT'			=> $this->input->post('id_penerbit'),
			'TAHUN_TERBIT'			=> $this->input->post('tahun_terbit'),
			'TGL_MASUK'				=> date('Y-m-d'),
			'JUMLAH'				=> $this->input->post('jumlah'),
			'HARGA_SATUAN'			=> $this->input->post('harga_satuan'),
			'ABSTRAKSI'				=> $this->input->post('abstraksi'),
			'KETERANGAN'	 		=> $this->input->post('keterangan'),
			
			'HAL_ROMAWI'	 		=> $this->input->post('hal_romawi'),
			'HAL_ANGKA'	 			=> $this->input->post('hal_angka'),
			'ILUSTRASI'	 			=> $this->input->post('ilustrasi'),
			'INDEX'	 				=> $this->input->post('index'),
			'DIMENSI_BUKU'	 		=> $this->input->post('dimensi'),
			// 'COVER_BUKU'	 		=> $_FILES['cover_buku']['name']
		);
		$ins_cover = $this->pustaka_model->insert_buku($data);
		$id_buku = $this->pustaka_model->getLastPustaka()->row();
		for($i=1; $i<=$this->input->post('jumlah');$i++){
			$data = array(
				'ID_SEKOLAH'			=> $nama_sekolah,
				'ID_BUKU'				=> $id_buku->maxid,
				'KODE_EKSEMPLAR'		=> $this->refrensi_model->get_jenisID($this->input->post('id_jenis'))->row()->KODE_JENIS.'/'.(int)($this->input->post('kode_buku')).'/'.str_pad($i,3, "0", STR_PAD_LEFT).'/'.substr($this->refrensi_model->get_penulisID($this->input->post('id_penulis'))->row()->NAMA_PENULIS,0,3).'/'.substr($this->input->post('judul_buku'),0,1),
				'STATUS'				=> 1 //ada
			);
			$this->pustaka_model->insert_eksemplar($data);
		}
		
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		if($ins_cover == true){
			if($_FILES['userfile']['name']!= ''){
				$config['file_name'] = $this->input->post('kode_buku');
				$config['upload_path'] = './uploads/pustaka/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg';
				$config['max_size']	= '500';
				$this->upload->initialize($config);
				$this->load->library('upload', $config);
				
				if ( ! $this->upload->do_upload()){
					$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
					$data['status'] = 'edit';
					$data['rs_buku'] = $this->pustaka_model->get_bukuID((int)$this->input->post('kode_buku'));
					$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
					$data['katalog'] = $this->refrensi_model->get_list_katalog();
					$data['penulis'] = $this->refrensi_model->get_list_penulis();
					$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
					$data['content'] = $this->load->view('perpus/form_buku',$data,true);
					$this->load->view('main',$data);
				}
				else {	
						$data2 = array();
						$data2['COVER_BUKU'] = $this->input->post('kode_buku').'.'.$filenamess;
						$this->pustaka_model->update_buku($data2,(int)$this->input->post('kode_buku'));
						
						$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
						redirect('perpus/list_buku');
					}				
			}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('perpus/list_buku');
				}
		}
		
		// $this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
		// redirect('perpus/list_buku'); 
	}
	
	function edit_buku($id_buku)
    {
 		if ($this->cek_validasi() == FALSE){
				$data['status'] = 'edit';
				$data['rs_buku'] = $this->pustaka_model->get_bukuID($id_buku);
				$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
				$data['katalog'] = $this->refrensi_model->get_list_katalog();
				$data['penulis'] = $this->refrensi_model->get_list_penulis();
				$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
				$data['kodebuku'] = '' ;
				
				$data['content'] = $this->load->view('perpus/form_buku',$data,true);
				$this->load->view('main',$data);
			}
			else{
				if($this->cek_buku($this->input->post('kode_buku'))->jml > 0 and $this->cek_buku($this->input->post('kode_buku'))->ID_BUKU != $id_buku ){
					$data['status'] = 'edit';
					$data['rs_buku'] = $this->pustaka_model->get_bukuID($id_buku);
					$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
					$data['katalog'] = $this->refrensi_model->get_list_katalog();
					$data['penulis'] = $this->refrensi_model->get_list_penulis();
					$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
					
					$data['value'] = $this->input->post();
					$data['err_msg'] = 'Data Pustaka telah ada dalam database.';
					$data['content'] = $this->load->view('perpus/form_buku',$data,true);
					$this->load->view('main',$data);
				}else{
					$this->update_buku($id_buku);
				}
			}            
    }
	
	function update_buku($id_buku){
		if($this->session->userdata('roleid')=='0'){ //diknas
			$nama_sekolah = $this->input->post('nama_sekolah');
		}else{
			$nama_sekolah = $this->session->userdata('unitid');
		}
	
		$data = array(
			'ID_SEKOLAH'			=> $nama_sekolah,
			// 'KODE_BUKU'				=> $this->input->post('kode_buku'),
			'JUDUL_BUKU'			=> $this->input->post('judul_buku'),
			'ID_JENIS'				=> $this->input->post('id_jenis'),
			'ID_KATALOG'			=> $this->input->post('id_katalog'),
			'ID_PENULIS'			=> $this->input->post('id_penulis'),
			'ID_PENERBIT'			=> $this->input->post('id_penerbit'),
			'TAHUN_TERBIT'			=> $this->input->post('tahun_terbit'),
			'TGL_MASUK'				=> date('Y-m-d'),
			'JUMLAH'				=> $this->input->post('jumlah'),
			'HARGA_SATUAN'			=> $this->input->post('harga_satuan'),
			'ABSTRAKSI'				=> $this->input->post('abstraksi'),
			'KETERANGAN'	 		=> $this->input->post('keterangan'),
			'HAL_ROMAWI'	 		=> $this->input->post('hal_romawi'),
			'HAL_ANGKA'	 			=> $this->input->post('hal_angka'),
			'ILUSTRASI'	 			=> $this->input->post('ilustrasi'),
			'INDEX'	 				=> $this->input->post('index'),
			'DIMENSI_BUKU'	 		=> $this->input->post('dimensi'),
			// 'COVER_BUKU'	 		=> $_FILES['cover_buku']['name']
		);
		$this->pustaka_model->update_buku($data,$id_buku);
		$filenamees = explode('.',$_FILES['userfile']['name']);
		$filenamess = $filenamees[count($filenamees)-1];
		
		if($_FILES['userfile']['name']!= ''){
			$config['file_name'] = $id_buku;
			$config['upload_path'] = './uploads/pustaka/';
			$config['allowed_types'] = 'gif|jpg|png|jpeg';
			$config['max_size']	= '1000';
			$this->upload->initialize($config);
			$this->load->library('upload', $config);
			
			//delete files //
			if($this->input->post('fileold')!= ''){
				unlink('uploads/pustaka/'.$this->input->post('fileold'));
			}
			
			if ( ! $this->upload->do_upload()){
				$data['err_msg'] = 'Maaf, file yang diupload tidak sesuai dengan format';
				$data['status'] = 'edit';
				$data['rs_buku'] = $this->pustaka_model->get_bukuID($id_buku);
				$data['jenis'] = $this->refrensi_model->get_list_jenis_buku();
				$data['katalog'] = $this->refrensi_model->get_list_katalog();
				$data['penulis'] = $this->refrensi_model->get_list_penulis();
				$data['penerbit'] = $this->refrensi_model->get_list_penerbit();
				$data['kodebuku'] = '' ;
				$data['content'] = $this->load->view('perpus/form_buku',$data,true);
				$this->load->view('main',$data);
			}
			else {	
					$data2 = array();
					$data2['COVER_BUKU'] = $id_buku.'.'.$filenamess;
					$this->pustaka_model->update_buku($data2,$id_buku);
					
					$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
					redirect('perpus/list_buku');
				}				
		}else {	$this->session->set_flashdata('suc_msg', 'Data berhasil disimpan.');
				redirect('perpus/list_buku');
			}
		
		// $this->session->set_flashdata('suc_msg', 'Data berhasil diupdate.');
		// redirect('perpus/list_buku'); 
	}
	
	//Delete
	function delete_buku()
	{
		$ta_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($ta_ids_post_array as $index => $ta_id){
			if (isset($ta_id) && $ta_id != "") {
				$this->pustaka_model->delete_buku($ta_id);
						
			
			$msg .= "Data Pustaka berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
	
	function tambah_eks($id_pustaka){
		$detail = $this->pustaka_model->get_bukuID($id_pustaka)->row();
		$data = array(
			'ID_SEKOLAH'			=> $this->session->userdata('unitid'),
			'ID_BUKU'				=> $detail->ID_BUKU,
			'KODE_EKSEMPLAR'		=> $detail->KODE_JENIS.'/'.str_pad($detail->JUMLAH + 1,7, "0", STR_PAD_LEFT).'/'.substr($detail->NAMA_PENULIS,0,3).'/'.substr($detail->JUDUL_BUKU,0,1),
			'STATUS'				=> 1
		);
		$this->pustaka_model->insert_eksemplar($data);
		redirect('perpus/list_buku');
	}
	
    function lihat_eks($idpustaka){
		$data['detail_pustaka'] = $this->pustaka_model->get_bukuID($idpustaka)->row();
		$data['detail_eks'] = $this->pustaka_model->get_eksemplarID($idpustaka);
		// $data['content'] = $this->load->view('perpus/form_detail_eksemplar',$data,true);
		$this->load->view('perpus/form_detail_eksemplar',$data);
	}
}
?>
